/**
 * Assignment 3               P3.java               Due: July 8, 2011 @ 6:00 am
 *
 * login: cs11ubn
 */

import java.util.*;

/**
 * Takes a given string of input and determines any anagrams in it. It will
 * output the anagrams then prompt to continue and find more.
 */
public class P3
{
  /**
   * Main method used as an entry point. Gathers input, calls method to find
   * anagrams, then outputs. Loops until 'n' or 'N' is given when prompted to
   * continue.
   */
  public static void main(String[] args)
  {
    // Declare our variables
    char choice; // Holds the choice to continue. Stop if equal to 'n' or 'N'
    String str; // Holds the input for choice
    String inputStr; // Holds the input of words to check for anagrams
    String sAnagram = null; // Holds the string of anagrams
    Scanner scan = new Scanner(System.in); // Holds the scanner for input
    
    do
    {
      // Prompt for input
      System.out.println(); // New line
      System.out.print("Enter your Anagrams:\t");
      
      inputStr = scan.nextLine(); // Read input
      
      String words[] = inputStr.split(" "); // Split based on spaces
      
      // Print what the user entered
      System.out.print("Sentence:\t\t");
      for (String iter : words)
      {
        System.out.print(iter + " ");
      }
      
      // Position cursor on next line
      System.out.println();
      
      sAnagram = anagrams(words); // Get the anagrams based on the split
      
      // Print out anagrams
      System.out.println("All Anagrams:\t\t" + sAnagram);
      
      // Prompt for continue
      System.out.print("All Anagrams (y/n)?  ");
      str = scan.next(); // Grab input from console
      choice = str.charAt(0); // Get the first letter of their choice
      
      // Check for <ENTER> character
      if (scan.hasNextLine())
      {
        // User pressed enter, discard
        str = scan.nextLine();
      }
    } while(choice != 'n' && choice != 'N');
    
    scan.close();
    System.exit(0);
  }
  
  /**
   * Sort letters in word, return sorted word. Returned word is in lowercase.
   */
  public static String sortString(String s)
  {
    // Get all of the letters in lower case, then convert the string into an
    // array of chars
    char[] a = s.toLowerCase().toCharArray();
    char tmp; // Holds the greater value
    
    // Do a bubble sort
    for (int i = 0; i < a.length - 1; ++i)
    {
      for (int j = a.length - 1; i < j; --j)
      {
        // Check to see if the spot directly below a[j] is greater.
        if (a[j-1] > a[j])
        {
          // a[j-1] is greater than a[j], swap their positions.
        
          tmp = a[j-1]; // Set tmp to the greater value
          
          a[j-1] = a[j]; // Set the grater values position to the lesser value
          
          a[j] = tmp; // Set the lesser values position to the greater value
        }
      }
    }
    
    // Set s to the now sorted array
    s = new String(a);
    
    return s; // Return the sorted string. Note that it is all lowercase
  }
  
  /**
   * Compare Strings and find anagrams. Output is the same case as recieved.
   */
  public static String anagrams(String[] a)
  {
    // Declare our variables
    String[] aSortedStrg = new String[a.length]; // Array of sorted strings
    String checkedAnagrams = ""; // Output string, holds the anagrams
    String currentWord; // Holds the first word to compare
    String compare; // Holds the second word to compare
    boolean currentWordAdded; // Used to make sure we only enter the first word
                              // once
    
    // Iterate through the strings and store their sorted versions in 
    // aSortedStrg
    for (int i = 0; i < a.length; i++)
    {
      // Store the sorted string in the sorted array
      aSortedStrg[i] = sortString(a[i]);
    }

    // Iterate through aSortedStrg and check all words further down for anagrams
    for (int i = 0; i < aSortedStrg.length; i++)
    {
      currentWord = aSortedStrg[i]; // Grab the current word
      aSortedStrg[i] = ""; // Set its position to empty string to prevent repeat
      
      currentWordAdded = false; // The new first word is not added
      
      // Loop through the rest of the strings
      for (int j = i + 1; j < aSortedStrg.length; j++)
      {
        // Grab the word to compare against
        compare = aSortedStrg[j];
      
        if (currentWord.equals(compare) && currentWord != "")
        {
          // System.out.println(currentWord + " = " + compare);
        
          // See if we need to add the first word
          if (!currentWordAdded)
          {
            checkedAnagrams += a[i] + " ";
            currentWordAdded = true; // Make sure we don't add it again
          }
          
          // Add the compared word to the output strings
          checkedAnagrams += a[j] + " ";
          
          // Set the added word to an empty string to prevent multiple additions
          aSortedStrg[j] = "";
        }
      }
    }
    
    return checkedAnagrams;
  }
}
